package com.easychat.redis;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
//@Slf4j
public class RedisConfig<V> {

    //redis host
    @Value("${spring.redis.host:}")
    private String redisHost;
    //redis端口
    @Value("${spring.redis.port:}")
    private Integer redisPort;

    @Bean
    public RedisTemplate<String,V> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        //log.info("开始创建redis模板对象");
        RedisTemplate<String,V> redisTemplate = new RedisTemplate<>();
        //设置连接工厂对象
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //设置redis key的序列化器
        redisTemplate.setKeySerializer(RedisSerializer.string());
        //设置value的序列化
        redisTemplate.setValueSerializer(RedisSerializer.json());
        //设置hash key的序列化
        redisTemplate.setHashKeySerializer(RedisSerializer.string());
        //设置hash value的序列化
        redisTemplate.setHashValueSerializer(RedisSerializer.json());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean(name = "redissonClient", destroyMethod = "shutdown")
    public RedissonClient redissonClient() {
        try {
            Config config = new Config();
            config.useSingleServer().setAddress("redis://" + redisHost + ":" + redisPort);
            RedissonClient redissonClient = Redisson.create(config);
            return redissonClient;
        } catch (Exception e) {
            //log.error("Redisson配置错误");
            return null;
        }
    }
}
